package com.sendmsg.controller;

import com.sendmsg.entity.Msg;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties;

/**
 * @author: Combo
 * @time: 2021/1/7 18:08
 * @description: 发送带附件的邮件
 */
public class SendRichText {

    public void Send(File file) {
        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", Msg.HOST);

        // 用户认证
        properties.put("mail.smtp.auth", true);

        // 获取默认的session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            // 用户认证
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 发件人邮箱用户名、授权码
                return new PasswordAuthentication(Msg.FORM, Msg.AUTH_CODE);
            }
        });
        // 消息
        MimeMessage message = new MimeMessage(session);
        try {
            // 发送至
            message.setFrom(new InternetAddress(Msg.FORM));
            // 谁发的
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(Msg.TO));
            // 正文标题
            message.setSubject("biubiubiu");
            // 消息体
            BodyPart bodyPart = new MimeBodyPart();
            // 文字消息
            bodyPart.setText("我是正文开始");
            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 将文本消息加入
            multipart.addBodyPart(bodyPart);
            // 附件
            bodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(file);
            bodyPart.setDataHandler(new DataHandler(source));
            // 设置文件名
            bodyPart.setFileName(file.getName());
            multipart.addBodyPart(bodyPart);

            message.setContent(multipart);
            // 发送消息
            Transport.send(message);
            System.out.println("哔哩哔哩 (゜-゜)つロ 干杯~-bilibili 发送成功！");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
